<?php

namespace app\admin\controller\vppz;

use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Area extends Base
{

    /**
     * Area模型对象
     * @var \app\admin\model\vppz\Area
     */
    protected $model = null;

	protected $searchFields = ['id','name','city','district'];
	protected $multiFields = ['use_switch'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\Area;
        $this->view->assign("odmodeList", $this->model->getOdmodeList());
        $this->view->assign("staffRegList", $this->model->getStaffRegList());
		$this->view->assign("sellerRegList", $this->model->getSellerRegList());
        $this->view->assign("staffTeamList", $this->model->getStaffTeamList());
		$this->view->assign("staffCardList", $this->model->getStaffCardList());

		// 给数据附加当前appid，appid由Base负责解析
		$this->model::event('before_insert', function ($row){
			$row->app_id=$this->app_id;
		});

		$this->model::event('before_insert', function ($row){return $this->beforeSave($row);});
		$this->model::event('before_update', function ($row){return $this->beforeSave($row);});
    }

	// 处理前端输入的城市，分为三段存储
	protected function beforeSave($row){
		if(in_array($this->request->action(),['add','edit'])){
			$city = explode('/',$row->city);
			if(count($city)<2){
				//$this->error('请选择到区');
				//echo '测试';
				exception('请至少选择到城市级');
				return false;
			}
			$row->province=$city[0];
			$row->city=$city[1];
			$row->district=isset($city[2])?$city[2]:'';
		}
	}

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

	/**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

		$adminAreasWhere=$this->adminAreasWhere('id');
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {

			//$list = $this->model->field('id,name')->where(['app_id'=>$this->app_id,'use_switch'=>1])->where($adminAreasWhere)->select();

			//return json(['list' => $list,'total' => count($list)]);
			return $this->selectpage_custom();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model
            ->where($where)->where($adminAreasWhere)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


	/**
	 * 重载selectpage，实现对管理员权限的过滤
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage_custom()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }

				// 自定义管理员权限筛选
				$adminAreasWhere=$this->adminAreasWhere('id');
				$query->where($adminAreasWhere);
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }

        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }


	/**
     * 结算
     */
    public function settle()
    {
		$ids = input('ids');
        $area = $this->model->get(['id' => $ids]);
        if (!$area) {
            $this->error(__('No Results were found'));
        }

		if ($this->request->isAjax()) {
			$row = input('row/a');

			if($row['outcash']>$area['money']){
				 $this->error('结算金额不能超出余额');
			}

			$ret = Db::name('vppz_area')->where(['app_id'=>$this->app_id,'id'=>$area['id']])->dec('money',$row['outcash'])->inc('money_outcash',$row['outcash'])->update();
			if(!($ret>0)){
				$this->error("操作失败，请重试");
			}

			$this->recordMoney([
				'who'=>'area',
				'who_id'=>$area['id'],
				'who_name'=>$area['name'],
				'user_id'=>$area['user_id'],
				'money'=> 0-$row['outcash'],
				'biz'=>'settle',
				'biz_id'=>$area['id'],
				'biz_type'=>'area',
				'biz_name'=>'结算',
				'remark'=>$row['remark']
			]);


			$this->success("保存成功");
		}else{


			$this->view->assign("row", $area);
			return $this->view->fetch();
		}
    }

}
